package com.beiing.tianshuai.tianshuai.huodong;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageButton;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.activity.MainActivity;
import com.beiing.tianshuai.tianshuai.activity.NewDiscoveryPublishActivity;
import com.beiing.tianshuai.tianshuai.app.AppConstant;
import com.beiing.tianshuai.tianshuai.base.BaseFragment;
import com.beiing.tianshuai.tianshuai.entity.EventTypesBean;
import com.beiing.tianshuai.tianshuai.entity.UserInfoBean;
import com.beiing.tianshuai.tianshuai.huodong.adapter.MyPagerAdapter;
import com.beiing.tianshuai.tianshuai.huodong.presenter.EventsPresenter;
import com.beiing.tianshuai.tianshuai.huodong.view.EventsViewImpl;
import com.beiing.tianshuai.tianshuai.huodong.view.EventsCommonFragment;
import com.beiing.tianshuai.tianshuai.mine.ui.LoginActivity;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.widget.CustomEmptyLayout;
import com.flyco.tablayout.SlidingTabLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 活动主界面
 *
 * @author Jinda Yang
 * @date 2018/5/30
 */
public class EventsFragment extends BaseFragment implements EventsViewImpl {

    /**
     * toolbar菜单按钮
     */
    @BindView(R.id.toolbar_btn_publish)
    ImageButton toolbarBtnPublishEvent;

    /**
     * empty layout
     */
    @BindView(R.id.cel_empty_layout)
    CustomEmptyLayout celEmptyLayout;

    /**
     * 活动类型选择器
     */
    @BindView(R.id.sliding_tab)
    SlidingTabLayout stSlidingTabLayout;

    /**
     * 活动列表fragment view pager容器
     */
    @BindView(R.id.events_fragment_container)
    ViewPager vpEventFragmentsViewPager;


    private static final String TAG = "EventsFragment";

    /**
     * 活动主页面presenter
     */
    private EventsPresenter mPresenter;

    /**
     * 活动列表碎片
     */
    private ArrayList<Fragment> mFragments = new ArrayList<>();

    /**
     * 重连次数
     */
    private int reconnectionTimes = 0;

    public static EventsFragment getNewInstance() {
        EventsFragment eventsFragment = new EventsFragment();
        Bundle bundle = new Bundle();
        eventsFragment.setArguments(bundle);
        return eventsFragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_events;
    }

    @Override
    protected void init(View convertView) {
        initPresenter();
        initListener();
    }

    /**
     * 实例化presenter
     */
    private void initPresenter() {
        mPresenter = new EventsPresenter(this);
        mPresenter.getEventTypes(UserInfoBean.getUid(mContext));
    }

    /**
     * 初始化监听事件
     */
    private void initListener() {
        // empty layout retry btn click listener
        celEmptyLayout.setRetryListener(new CustomEmptyLayout.RetryListener() {
            @Override
            public void retry() {
                mPresenter.getEventTypes(UserInfoBean.getUid(mContext));
            }
        });

        // 发布按钮点击事件
        toolbarBtnPublishEvent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String uid = UserInfoBean.getUid(mContext);
                if (!TextUtils.isEmpty(uid)) {
                    String attestation = UserInfoBean.getAttestation(mContext);
                    switch (attestation) {
                        case "4":
                            Intent intent = new Intent(mContext, NewDiscoveryPublishActivity.class);
                            intent.putExtra("type", 0);
                            startActivity(intent);
                            break;
                        case "2":
                        case "3":
                        default:
                            showShortText("“组织认证/企业认证”用户才可以发布噢~");
                            break;
                    }
                } else {
                    startActivity(new Intent(mContext, LoginActivity.class));
                }
            }
        });
    }

    /**
     * 显示加载状态
     */
    @Override
    public void showProgress() {
        if (celEmptyLayout != null) {
            celEmptyLayout.setInProgress();
        }
    }

    /**
     * 隐藏加载状态
     */
    @Override
    public void hideProgress() {
        if (celEmptyLayout != null) {
            celEmptyLayout.setChildrenVisible();
        }
    }

    /**
     * 请求活动分类成功
     *
     * @param bean 活动分类数据实体
     */
    @Override
    public void onRequestSuccess(EventTypesBean bean) {
        reconnectionTimes = 0;
        LogUtils.d(bean.toString(), TAG);
        int code = bean.getCode();
        switch (code) {
            case 200:
                List<EventTypesBean.DataBean.NumberBean> beanList = bean.getData().getNumber();
                int typeNum = beanList.size();
                String[] tabTitles = new String[typeNum + 1];
                tabTitles[0] = "全部活动";
                for (int i = 0; i < typeNum; i++) {
                    tabTitles[i + 1] = beanList.get(i).getName();
                }
                String[] ids = new String[typeNum];
                for (int i = 0; i < typeNum; i++) {
                    ids[i] = beanList.get(i).getId();
                }
                mFragments.add(new AllEventsFragment());
                for (int i = 0; i < tabTitles.length - 1; i++) {
                    mFragments.add(EventsCommonFragment.newInstance(ids[i]));
                }
                MyPagerAdapter adapter = new MyPagerAdapter(
                        ((MainActivity) mContext).getSupportFragmentManager(), mFragments, tabTitles);
                vpEventFragmentsViewPager.setAdapter(adapter);
                vpEventFragmentsViewPager.setOffscreenPageLimit(2);
                stSlidingTabLayout.setViewPager(vpEventFragmentsViewPager);
                break;
            default:
                if (celEmptyLayout != null) {
                    celEmptyLayout.setChildrenGone();
                }
                showShortText("未知请求异常");
                break;
        }
    }

    /**
     * 请求活动分类失败
     *
     * @param throwable 异常
     */
    @Override
    public void onRequestFailed(Throwable throwable) {
        if (reconnectionTimes < AppConstant.MAX_RECONNECTION_TIMES) {
            mPresenter.getEventTypes(UserInfoBean.getUid(mContext));
            reconnectionTimes++;
        } else {
            if (celEmptyLayout != null) {
                celEmptyLayout.setChildrenGone();
            }
            LogUtils.e(throwable, throwable.getMessage(), TAG);
        }
    }
}